class Ad < ActiveRecord::Base
  #
  # Relations
  #

  belongs_to :board, :class_name => "Board"
  belongs_to :user, :class_name => "User"
  has_many :offers
  has_and_belongs_to_many :tags

  has_attached_file :picture, :styles => { :medium => "300x300>", :thumb => "80x80>" }

  #
  # Validation
  #

  validates :label, :presence => true
  validates :description, :presence => true
  validates :cost, :presence => true
  validates :tags, :presence => true

  validates_associated :board
  validates_associated :tags

  #
  # Methods
  #

  def initialize(params=nil)
    if params
      params[:user] = User.current
      params[:board] = Board.find_by_label(params[:board])
      params[:enabled] = true

      tags = []
        for label in params[:tags].split(',')
          if tag != '[]' # patch to resolve a display bug
            tag = Tag.find_by_label(label) || Tag.new({:label => label})
            tag.save
            tags << tag
          end
      end
      params[:tags] = tags
    end
    super
  end

  def after_initialize
    self.money = 100 # default peaksel sum
  end

  def disable!
    self.update_attributes(:enabled => false)
  end

  def update_attributes(params)
    if params[:board]
      params[:board] = Board.find_by_label(params[:board])
    end
    super
  end

  def to_s
    self.label
  end
end
